package terra.model.object;

import terra.definitions.NpcDef;
import terra.managers.DefManager;
import terra.model.World;
import terra.model.object.interfaces.Attackable;
import terra.model.object.interfaces.Attacker;
import terra.model.object.interfaces.Interactable;
import terra.model.object.interfaces.Touchable;
import terra.model.object.map.AbstractMapObject;
import terra.network.packet.Packet;
import terra.network.packet.server.DoorInfo;

public class Door extends StaticObject implements Interactable, Attackable, Touchable {

	private static final long serialVersionUID = -1040677093548466855L;
	private boolean opened = false;
	private long lastChanged = 0;
	private int health;
	
	public Door(NpcDef def) {
		this(World.getNextId(),def);
	}

	public Door(int objectId,int def) {
		this(objectId,DefManager.npcDefs.get(def));
	}
	
	public Door(int objectId,NpcDef def) {
		super(objectId);
		setDefId(def.id);
		setImage(def.getStringProperty("image"));
		setWidth(def.getIntProperty("width"));
		setHeight(def.getIntProperty("height"));
		health = def.getIntProperty("baseHp");
	}

	@Override
	public void onClick(int button, Player player) {
		if (lastChanged+500 < System.currentTimeMillis()){
			if(!isCollisionWithObjects(getX(), getY()))
				setOpened(!isOpened());
			lastChanged = System.currentTimeMillis();
		}
	}

	@Override
	public void onTouch(GameObject object) {
//		if (!isOpened()){
//			object.setX(object.getOldX());
//			object.setY(object.getOldY());
//			object.setYacceleration(0);
//			System.out.println("Object touch door " + object);
//		}
		//System.out.println("Object touch door " + object);
	}
	
	@Override
	public boolean isSolid(GameObject object) {
		return !isOpened();
	}

	public boolean isOpened() {
		return opened;
	}

	public void setOpened(boolean opened) {
		this.opened = opened;
		changeState();
	}

	private void changeState() {
		getMap().send(getInfo(), true);
	}

	@Override
	public void onHit(Attacker damager, float damage) {
		health -= damage;
		if (health <= 0)
			die(damager);
	}

	@Override
	public void die(Attacker killer) {
		removeObject();
		World.getInstance().removeObject(this);
	}

	@Override
	public void update(int delta) {
	}

	public boolean makeDoor(AbstractMapObject abstractMapObject) {
		setX(abstractMapObject.getX());
		setY(abstractMapObject.getY());
		setName("Door");
		return true;
	}

	@Override
	public boolean isDead() {
		return isRemove();
	}

	@Override
	public Packet getInfo() {
		DoorInfo info = new DoorInfo();
		info.x = getX();
		info.y = getY();
		info.id = getDefId();
		info.oId = getObjectId();
		info.open = (byte) (isOpened() ? 1 : 0);
		return info;
	}


	@Override
	public void applyDef() {
	}

}
